﻿package at.geoathome.utils
{
	import com.kronomy.utils.loader.XMLLoader;
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	
	/**
	 * ...
	 * @author Georg Kamptner
	 * This class is implemented as Singleton.
	 */
	public class SWFConfig extends EventDispatcher
	{
		// protected but public accessible fields
		protected var _web_path:String;
		protected var _storage_path:String;
		protected var _language_path:String;
		// protected
		protected var _config_file_url:String;
		protected var _xml_loader:XMLLoader;
		
		// static private
		private static var _instance:SWFConfig;
		
		
		// -- getter & setter --------------------------------------------------------------------------
		public function get web_path():String { return _web_path; }
		
		public function set web_path(value:String):void 
		{
			_web_path = value;
		}
		
		public function get storage_path():String { return _storage_path; }
		
		public function set storage_path(value:String):void 
		{
			_storage_path = value;
		}
		
		public function get language_path():String { return _language_path; }
		
		public function set language_path(value:String):void 
		{
			_language_path = value;
		}
		
		// -- Singleton ------------------------------------------------------------------------------------
		public static function getInstance():SWFConfig
		{
		  if (_instance == null)
			_instance = new SWFConfig(new SingletonEnforcer());
			
		  return _instance;
		}
		
		// -- class ---------------------------------------------------------------------------------------
		public function SWFConfig(singleton_enforcer:SingletonEnforcer) 
		{	
			_web_path 		= "";
			_storage_path 	= "";
			_language_path 	= "";
		}
		
		/**
		 * loads an xml file from the specified url. if you specified it already in the constructor you can omit it.
		 */
		public function load(config_file_url:String):void
		{
			_config_file_url = config_file_url;
			
			if (_config_file_url == null || _config_file_url == "")
				throw new IOError("Config File has not been found (config_file_url is invalid).");
			
			_xml_loader = new XMLLoader(_config_file_url);
			_xml_loader.addEventListener(Event.COMPLETE, _onXMLLoadComplete);
			_xml_loader.addEventListener(IOErrorEvent.IO_ERROR, _delegate);
			_xml_loader.load();
		}
		
		protected function _onXMLLoadComplete(e:Event):void
		{
			var xml:XML = e.target.getResult();
			
			_web_path 		= xml.webPath.@url;
			_storage_path 	= xml.storagePath.@url;
			_language_path 	= xml.languagePath.@url;
			
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		/**
		 * simply delegates the event
		*/
		protected function _delegate( event:Event ):void
		{
			dispatchEvent(event);
		}
		
		
		
	}	
}

class SingletonEnforcer {}

